package repository.relsys.services;

import java.util.Collection;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import repository.relsys.domainmodel.general.Resource;
import repository.relsys.services.datacentral.DataProvider;

import thewebsemantic.Bean2RDF;
import thewebsemantic.RDF2Bean;

import com.hp.hpl.jena.rdf.model.Model;

public class DefaultRelsysService implements RelsysService {

	protected DataProvider dataProvider;
	protected Bean2RDF writer;
	protected RDF2Bean reader;
	protected Model dataSource;
	protected DataModelManager manager = new DataModelManager();

	public void initialize() {
		this.dataSource = manager.getDataModel();
		this.writer = manager.getWriter();
		this.reader = manager.getReader();
	}

	public DefaultRelsysService() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public <T extends Resource> void deleteResource(Class<T> clazz,
			String resourceURI, boolean deep) throws Exception {
		// TODO Auto-generated method stub
		LinkedList<T> list = (LinkedList<T>) loadAllResources(clazz, deep);

		Iterator<T> iter = list.iterator();

		while (iter.hasNext()) {
			T t = (T) iter.next();

			if (((Resource) t).getURI().equals(resourceURI)) {
				deleteResource(t);
				break;
			}
		}
	}

	@Override
	public <T extends Resource> void deleteResource(T t) throws Exception {
		// TODO Auto-generated method stub
		writer.delete(t);

		dataProvider.updateDataSource(dataSource);
	}

	@Override
	public <T extends Resource> Collection<T> loadAllResources(Class<T> clazz,
			boolean loadDeep) throws Exception {
		// TODO Auto-generated method stub
		if (loadDeep)
			return reader.loadDeep(clazz);
		else
			return reader.load(clazz);
	}

	@Override
	public <T extends Resource> T loadResource(Class<T> clazz,
			String resourceURI, boolean loadDeep) throws Exception {
		// TODO Auto-generated method stub
		if (loadDeep)
			return reader.loadDeep(clazz, resourceURI);
		else
			return reader.load(clazz, resourceURI);
	}

	@Override
	public <T extends Resource> Collection<T> loadResources(Class<T> clazz,
			Collection<String> resourceURIs, boolean loadDeep) throws Exception {
		// TODO Auto-generated method stub
		List<T> resources = new LinkedList<T>();
		Iterator<String> iter = resourceURIs.iterator();

		while (iter.hasNext()) {
			resources.add(loadResource(clazz, iter.next(), loadDeep));
		}

		return resources;
	}

	@Override
	public <T extends Resource> void saveResource(T t, boolean deep)
			throws Exception {
		// TODO Auto-generated method stub
		if (deep)
			writer.saveDeep(t);
		else
			writer.save(t);

		dataProvider.updateDataSource(dataSource);
	}

	@Override
	public <T extends Resource> void updateResource(T t, boolean deep)
			throws Exception {
		// TODO Auto-generated method stub
		if (deep)
			writer.saveDeep(t);
		else
			writer.save(t);

		dataProvider.updateDataSource(dataSource);
	}
}
